import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProFormDigit,
  ProFormText,
  ProFormTreeSelect,
  ProTable
} from "@ant-design/pro-components";
import React, {useRef, useState} from "react";
import {Button, Form} from "antd";
import {ApartmentOutlined, EditOutlined, PlusOutlined, SettingFilled} from "@ant-design/icons";
import {globalApi, globalLoadTableApi, handleGloblApi} from "@/services/admin-api/globalApi";

type Role = {
  roleId: number;
  roleName: string;
  roleCode: string;
  delFlag: boolean;
  createTime: string;
  createUserId: number;
  createUserName: string;
  updateTime: string;
  updateUserId: number;
  updateUserName: string;
};

export default () => {

  const [modalOpen, handleModalOpen] = useState(false);
  const [modalAuthOpen, handleAuthModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [authForm] = Form.useForm();
  const actionRef = useRef<ActionType>();
  // const [currentRow, setCurrentRow] = useState<ProductType>();

  const columns: ProColumns<Role>[] = [
    // {title: '', valueType: 'indexBorder'},
    {title: 'roleId', dataIndex: 'roleId', valueType: 'digit'},
    {title: 'roleName', dataIndex: 'roleName', valueType: 'text'},
    {title: 'roleCode', dataIndex: 'roleCode', valueType: 'text',},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      render: (_, record) => [
        <Button
          key={'edit_' + record.roleId} size="small" icon={<EditOutlined/>} type="primary"
          onClick={async () => {
            form.setFieldsValue({...record});
            handleModalOpen(true);
          }}
        />,
        <Button
          key={'edit_auth_' + record.roleId} size="small" icon={<ApartmentOutlined/>} type="primary"
          onClick={async () => {
            // form.setFieldsValue({...record});
            // handleModalOpen(true);
            handleAuthModalOpen(true)

            setTimeout(async () => {
              const r = await globalApi('/sys/getAuths', {roleId: record.roleId})
              // authForm.setFieldsValue({authIds: r.data})
              console.log('r = ', r)
              authForm.setFieldsValue({roleId: record.roleId, authIds: r.data})
            })
          }}
        />,
      ],
      valueType: 'option',
    },
  ];

  return <PageContainer header={{title: '', breadcrumb: {},}}>
    <ProTable<Role>
      columns={columns} actionRef={actionRef}
      search={{span: 4}}
      headerTitle={
        <Button
          key="primary" type="primary" icon={<PlusOutlined/>} onClick={() => {
          handleModalOpen(true)
        }}/>
      }
      request={async (param) => globalLoadTableApi('/sys/roleTable', param)}
      rowKey={(record) => record.roleId}
      columnsState={{
        defaultValue: {
          delFlag: {show: false},
          createUserId: {show: false},
          updateUserId: {show: false}
        }
      }}/>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={modalOpen} onOpenChange={handleModalOpen} form={form}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/sys/roleSaveOrUpdate', value)

        if (success) {
          actionRef.current?.reload();
          return true
        }

      }}
    >
      <ProFormDigit label="roleId" name="roleId" hidden/>
      <ProFormText label="roleName" rules={[{required: true}]} name="roleName"/>
      <ProFormText label="roleCode" rules={[{required: true}]} name="roleCode"/>

    </ModalForm>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={modalAuthOpen} onOpenChange={handleAuthModalOpen} form={authForm}
      onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/sys/roleAuths', value)

        if (success) {
          // actionRef.current?.reload();
          return true
        }

      }}
    >
      <ProFormDigit label="roleId" name="roleId" hidden/>
      <ProFormTreeSelect label="authIds" name="authIds" rules={[{required: true}]} request={async () => {
        const r = await globalApi('/sys/roleAuthTree', {})
        return r.data
      }} fieldProps={{showSearch: true, multiple: true, treeCheckable: true, treeLine: true}}/>
    </ModalForm>

  </PageContainer>
}
